package com.maixy.redisdemo.utils;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @ClassName RedisLockUtil
 * @Description TODO
 * @Date 2021/5/16 20:29
 * @Author maixy
 */
@Component
public class RedisLockUtil {

    @Autowired
    private RedissonClient redissonClient;

    public RLock lock(String lockKey) {
        RLock rLock = redissonClient.getLock(lockKey);
        rLock.lock();
        return rLock;
    }

    public RLock lock(String lockKey, int leaseTime) {
        RLock rLock = redissonClient.getLock(lockKey);
        rLock.lock(leaseTime, TimeUnit.SECONDS);
        return rLock;
    }

    /**
     * 获得锁
     * 拿不到lock就不罢休，不然线程就一直block。 比较无赖的做法。
     *
     * @param lockKey 锁key
     * @param timeUnit 时间单位
     * @param leaseTime 锁失效的时间
     * @return org.redisson.api.RLock
     */
    public RLock lock(String lockKey, TimeUnit timeUnit, int leaseTime) {
        RLock rLock = redissonClient.getLock(lockKey);
        rLock.lock(leaseTime, timeUnit);
        return rLock;
    }

    /**
     * 尝试获取锁
     * 马上返回，拿到lock就返回true，不然返回false。 比较潇洒的做法。
     * 带时间限制的tryLock()，拿不到lock，就等一段时间，超时返回false。比较聪明的做法。
     *
     * @param lockKey 锁key
     * @param unit 时间单位
     * @param waitTime 如果拿不到锁等待的时间
     * @param leaseTime 锁失效的时间
     * @return true=获取锁成功 false=未获取到锁
     */
    public boolean tryLock(String lockKey, TimeUnit unit, int waitTime, int leaseTime) {
        RLock lock = redissonClient.getLock(lockKey);
        try {
            return lock.tryLock(waitTime, leaseTime, unit);
        } catch (InterruptedException e) {
            return false;
        }
    }

    public void unlock(String lockKey) {
        RLock lock = redissonClient.getLock(lockKey);
        lock.unlock();
    }

    public void unlock(RLock lock) {
        lock.unlock();
    }

}
